#!/bin/bash

target=$1
file=$2

copy=1
recognized=0
closed=1
printed=0
wslines=0

matches()
{
    echo $line | grep $1 > /dev/null 2>&1
    return $?
}

wslines()
{
    [ $printed == 0 ] && return

    while [ $wslines -gt 0 ] ; do
        let wslines=$wslines-1
        echo ""
    done
}

targetre=`echo "^<.*$target.*>[[:space:]]*$"`
emptyre='^<>[[:space:]]*$'
elsere='^<else>[[:space:]]*$'
otherre='^<[^>]*>[[:space:]]*$'
blankre='^[[:space:]]*$'

while :
do
    read  -r line || break

    if matches $targetre ; then
        copy=1
        closed=0
        recognized=1
    elif matches $emptyre ; then
        copy=1
        closed=1
        recognized=0
    elif matches $elsere ; then
        closed=0
        let copy=!$recognized
    elif matches $otherre ; then
        closed=0
        copy=0
    elif [ $copy != 0 ] ; then
        if matches $blankre ; then
            [ $printed != 0 ] && let wslines=$wslines+1
            continue
        fi
        wslines
        echo $line
        printed=1
    fi
done

echo ""

if [ $closed == 0 ] ; then
    echo "Maybe no closing tag <> in $file" >&2
fi


